#ifndef _heapMgr_h_
#define _heapMgr_h_

// heapMgr.h
//
// Simple heap manager to reserve heap memory for low memory conditions

#include <new>

namespace simple{
    //
    // HeapMgr
    //
    // HeapMgr will initially allocate a block of memory to keep
    // in reserve. The size of this block is application dependent
    // and should be sized such that the memory is sufficient to
    // perform critical duties.
    //
    // In addition to being activated when new fails to allocate
    // memory, it can be manually called to release its memory.

    class HeapMgr
    {
    public:
        static HeapMgr& gOnly ();

        int  allocate (int desiredSize);
        void release  () { cleanup();}
        // Allocate or release the heap memory. This can be done
        // manually or in response to a low memory condition.
        // allocate() returns the number of bytes reserved

        void automatic (bool state) { _state = state;}
        // When set to true (the default), a low memory condition
        // will automatically release any reserved memory.

    private:
        static void newHandler ();
        // Our memory handler when new cannot allocate the desired memory

        static HeapMgr* _sOnly;

        HeapMgr ();

        void releaseMemory (); // Release reserve memory
        void cleanup ();       // Release our reserve and unhook our handler

        new_handler _oldHandler; // Previous handler
        bool        _state;      // true if we will automatically release memory
        bool        _nested;     // Detects if newHandler() is nested
        int         _size;       // Amount of memory (bytes) in reserve
        char*       _reserve;    // Reserve memory we keep
    };

}
#endif // _heapMgr_h_
